package com.yuan.app.pms.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.yuan.app.pms.dao.AttrAttrgroupRelationDao;
import com.yuan.app.pms.dao.AttrGroupDao;
import com.yuan.app.pms.dao.CategoryDao;
import com.yuan.app.pms.entity.AttrAttrgroupRelationEntity;
import com.yuan.app.pms.entity.AttrGroupEntity;
import com.yuan.app.pms.entity.vo.AttrPresInfoVo;
import com.yuan.app.pms.entity.vo.AttrPresVo;
import com.yuan.app.pms.entity.vo.AttrVo;
import com.yuan.app.pms.service.AttrAttrgroupRelationService;
import com.yuan.app.pms.service.CategoryService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuan.common.utils.PageUtils;
import com.yuan.common.utils.Query;

import com.yuan.app.pms.dao.AttrDao;
import com.yuan.app.pms.entity.AttrEntity;
import com.yuan.app.pms.service.AttrService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;
    @Autowired
    private AttrGroupDao attrGroupDao;
    @Autowired
    private CategoryDao categoryDao;
    @Autowired
    private AttrAttrgroupRelationService relationService;
    @Autowired
    private CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveAttr(AttrVo attrVo) {

        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVo, attrEntity);
        this.save(attrEntity);
        //获取属性分组id等，保存关联关系
        Long attrGroupId = attrVo.getAttrGroupId();
        Long attrId = attrVo.getAttrId();

        if (attrVo.getAttrType() == 1) {
            AttrAttrgroupRelationEntity relation = new AttrAttrgroupRelationEntity();

            relation.setAttrId(attrId);
            relation.setAttrGroupId(attrGroupId);

            attrAttrgroupRelationDao.insert(relation);
        }

    }

    @Override
    public PageUtils AttrList(Map<String, Object> params, Long catelogId, String type) {

        String key = (String) params.get("key");
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        if (type.equals("base")) {
            wrapper.eq("attr_type", 1);
        }
        if (type.equals("sale")) {
            wrapper.eq("attr_type", 0);
        }
        if (!StringUtils.isEmpty(key)) {
            wrapper.eq("attr_id", key).or().like("attr_name", key);
        }
        if (catelogId.longValue() != 0) {

            wrapper.eq("catelog_id", catelogId);
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params), wrapper
        );

        List<AttrEntity> records = page.getRecords();
        PageUtils pageUtils = new PageUtils(page);
        List<AttrPresVo> list = records.stream().map((attrEntity) -> {
                    AttrPresVo attrPresVo = new AttrPresVo();
                    BeanUtils.copyProperties(attrEntity, attrPresVo);
                    Long attrId = attrEntity.getAttrId();
                    Long attrGroupId = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>()
                            .eq("attr_id", attrId)).getAttrGroupId();


                    Long catelogId1 = attrEntity.getCatelogId();
                    String catelogName = categoryDao.selectById(catelogId1).getName();

                    attrPresVo.setCatelogName(catelogName);
                    if (type.equals("base")) {
                        String groupName = attrGroupDao.selectById(attrGroupId).getAttrGroupName();
                        attrPresVo.setGroupName(groupName);
                    }


                    return attrPresVo;
                }
        ).collect(Collectors.toList());

        pageUtils.setList(list);

        return pageUtils;


    }

    @Override
    public AttrPresInfoVo getArrt(Long attrId) {
        AttrEntity attr = this.getById(attrId);


        Long catelogId = attr.getCatelogId();

        //完整路径
        List<Long> path = new ArrayList<>();
        List<Long> list = establish(path, catelogId);
        Collections.reverse(list);

        Long[] longs = list.toArray(new Long[list.size()]);

        AttrPresInfoVo attrPresInfoVo = new AttrPresInfoVo();
        BeanUtils.copyProperties(attr, attrPresInfoVo);
        if (attr.getAttrType() == 1) {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationDao.selectById(attrId);
            if (attrAttrgroupRelationEntity != null) {
                Long attrGroupId = attrAttrgroupRelationEntity.getAttrGroupId();
                attrPresInfoVo.setAttrGroupId(attrGroupId);
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrGroupId);
                if (attrGroupEntity != null) {
                    attrPresInfoVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
        }
        attrPresInfoVo.setCatelogPath(longs);
        return attrPresInfoVo;


    }

    @Override
    public void updateAttrVo(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        this.updateById(attrEntity);

        //修改关联表
        AttrAttrgroupRelationEntity relation = new AttrAttrgroupRelationEntity();
        relation.setAttrId(attr.getAttrId());
        relation.setAttrGroupId(attr.getAttrGroupId());

        int count = relationService.count(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
        if (count > 0) {
            relationService.update(relation, new UpdateWrapper<AttrAttrgroupRelationEntity>()
                    .eq("attr_id", attr.getAttrId()));
        } else {
            relationService.save(relation);
        }


    }

    /**
     * 获取当前分组没有关联的所有属性
     * @param params
     * @param attrgroupId
     * @return
     */
    @Override
    public PageUtils getNoRelationAttr(Map<String, Object> params, Long attrgroupId) {
        //1、当前分组只能关联自己所属的分类里面的所有属性
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
        Long catelogId = attrGroupEntity.getCatelogId();
        //2、当前分组只能关联别的分组没有引用的属性
        //2.1)、当前分类下的其他分组
        List<AttrGroupEntity> group = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        List<Long> collect = group.stream().map(item -> {
            return item.getAttrGroupId();
        }).collect(Collectors.toList());

        //2.2)、这些分组关联的属性
        List<AttrAttrgroupRelationEntity> groupId = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", collect));
        List<Long> attrIds = groupId.stream().map(item -> {
            return item.getAttrId();
        }).collect(Collectors.toList());

        //2.3)、从当前分类的所有属性中移除这些属性；
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().eq("catelog_id", catelogId).eq("attr_type",1);
        if(attrIds!=null && attrIds.size()>0){
            wrapper.notIn("attr_id", attrIds);
        }
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            wrapper.and((w)->{
                w.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), wrapper);

        PageUtils pageUtils = new PageUtils(page);

        return pageUtils;
    }


    private List<Long> establish(List<Long> path, Long catelogId) {

        path.add(catelogId);
        Long parentCid = categoryService.getById(catelogId).getParentCid();
        if (parentCid != 0) {
            establish(path, parentCid);
        }


        return path;
    }


}